package com.hctforgreen.greenservice.ctr;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;

import com.hctforgreen.greenservice.db.DbAdapter;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.BookListEntity.MachineBooksEntity;
import com.hctforgreen.greenservice.model.BookTypeListEntity;
import com.hctforgreen.greenservice.model.BookTypeListEntity.BookTypeEntity;
import com.hctforgreen.greenservice.model.MachineListEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.Utils;

/**
 * db的控制器
 * 
 * @author Tallen Zhai
 * 
 */
public class DbController {

	private DbAdapter mDbAdapter;

	// private Activity mActivity;

	public DbController(Activity activity) {
		mDbAdapter = ((HctApplication) activity.getApplication()).getDbAdapter();
		// mActivity = activity;
	}

	public DbController(Context context) {
		mDbAdapter = ((HctApplication) context.getApplicationContext()).getDbAdapter();
		// mActivity = activity;
	}

	public DbController(DbAdapter dbAdapter) {
		mDbAdapter = dbAdapter;
	}

	// ============================
	// delete
	// ============================
	public boolean delete(MachineBooksEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from "
					+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST
					+ " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	public boolean delete(ChildSerieEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from "
					+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
					+ " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	public boolean delete(BookEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from " + HctConstants.DB_TABLE_NAME_BOOK_LST
					+ " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	public boolean delete(SerieEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from " + HctConstants.DB_TABLE_NAME_SERIE_LST
					+ " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	public boolean delete(MachineEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from "
					+ HctConstants.DB_TABLE_NAME_MACHINE_LST + " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	public boolean delete(BookTypeEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from "
					+ HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST + " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	// ============================
	// Entity insertOrUpdate
	// ============================
	public boolean insertOrUpdate(SerieEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}

	public boolean insertOrUpdate(MachineEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}

	public boolean insertOrUpdate(BookTypeEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}

	public boolean insertOrUpdate(ChildSerieEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}
/**
 * 更新或则插入MachineBooksEntity
 * @param entity
 * @return
 */
	public boolean insertOrUpdate(MachineBooksEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}

	public boolean insertOrUpdate(BookEntity entity) {
		if (isExists(entity)) {
			BookEntity inDbEntity = getBookEntityUseBookName(entity.bookName);
			if (!inDbEntity.versionCode.equals(entity.versionCode)) {
				entity.bCanUpdate = HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE;

				if (inDbEntity.currentBookFileLongSize.equals("")
						&& inDbEntity.currentBookId.equals("")) {
					entity.currentBookFileLongSize = inDbEntity.bookFileLongSize;
					entity.currentBookId = inDbEntity.id;

					update(entity, true);
				} else {
					update(entity);
				}

			} else if (inDbEntity.versionCode.equals(entity.versionCode)) {

				update(entity, false);
			}

		} else {
			insert(entity);
		}
		return true;
	}

	// ============================
	// ListEntity insert
	// ============================

	/**
	 * 插入BookListEntity，包括子系列下的books和机型下的books，
	 ** *即，将获取到的books数据，childSeriesBooks数据，machineBooks数据分别
	 * 插入到books表、childSeriesBooks表、machineBooks表
	 * 
	 * @param entities
	 * @return
	 */
	public boolean insert(BookListEntity listEntity) {
		boolean bState = false;
		mDbAdapter.beginTransaction();
		try {
			LogUtil.i("DATA","插入数据库");
			HctApplication.percent=10;

			deleteDeprecatedBookListEntity(listEntity);

			for (BookEntity entity : listEntity.dataList) {
				if (insertOrUpdate(entity)) {
					bState = true;
				}
			}
			//390778增加进度条
			int i = listEntity.dataList.size()+listEntity.childSeriesBooksList.size()
					+listEntity.machineBooksList.size();
			int per = 100*listEntity.dataList.size()/i;
			HctApplication.percent = per-10;


			deleteDeprecatedChildSeriesBooksListEntity(listEntity);
			for (ChildSerieEntity entity : listEntity.childSeriesBooksList) {
				if (insertOrUpdate(entity)) {
					bState = true;
				}
			}

			HctApplication.percent =per+100*listEntity.childSeriesBooksList.size()/i;
			deleteDeprecatedMachineBooksListEntity(listEntity);
			for (MachineBooksEntity entity : listEntity.machineBooksList) {
				if (insertOrUpdate(entity)) {
					bState = true;
				}
			}
			HctApplication.percent = HctApplication.percent+100*listEntity.machineBooksList.size()/i;
			mDbAdapter.setTransactionSuccessful();
		} finally {
			mDbAdapter.endTransaction();
		}

		return bState;
	}

	private void deleteDeprecatedChildSeriesBooksListEntity(
			BookListEntity listEntity) {
		List<ChildSerieEntity> inDbList = getChildSerieListEntityUseSerieId("",
				0);
		List<ChildSerieEntity> deprecatedList = new ArrayList<ChildSerieEntity>();
		if (inDbList == null) {
			return;
		}
		for (ChildSerieEntity inDbEntity : inDbList) {
			boolean bDeprecated = true;
			for (ChildSerieEntity inNetEntity : listEntity.childSeriesBooksList) {
				if (inDbEntity.childSeriesId.equals(inNetEntity.childSeriesId)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (ChildSerieEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	private void deleteDeprecatedMachineBooksListEntity(
			BookListEntity listEntity) {
		List<MachineBooksEntity> inDbList = getMachineBooksListEntity();
		List<MachineBooksEntity> deprecatedList = new ArrayList<MachineBooksEntity>();
		if (inDbList == null) {
			return;
		}
		for (MachineBooksEntity inDbEntity : inDbList) {
			boolean bDeprecated = true;
			for (MachineBooksEntity inNetEntity : listEntity.machineBooksList) {
				if (inDbEntity.machineId.equals(inNetEntity.machineId)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (MachineBooksEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	/**
	 * 删去已经废弃的Book
	 * 
	 * @param listEntity
	 *            刚刚从服务器获取到的最新BookListEntity
	 */
	private void deleteDeprecatedBookListEntity(BookListEntity listEntity) {
		BookListEntity inDbListEntity = getBookListEntityUseSerieId("", 0);
		List<BookEntity> deprecatedList = new ArrayList<BookEntity>();
		if (inDbListEntity.dataList == null) {
			return;
		}
		for (BookEntity inDbEntity : inDbListEntity.dataList) {
			boolean bDeprecated = true;
			for (BookEntity inNetEntity : listEntity.dataList) {
				if (inDbEntity.bookName.equals(inNetEntity.bookName)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (BookEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	/**
	 * 插入SerieListEntity
	 * 
	 * @param entities
	 * @return
	 */
	public boolean insert(SerieListEntity listEntity) {
		boolean bState = false;
		mDbAdapter.beginTransaction();

		try {
			deleteDbSerieListEntity();
			// deleteDeprecatedSerieListEntity(listEntity);

			for (SerieEntity entity : listEntity.dataList) {
				if (insert(entity)) {
					bState = true;
				}
			}
			mDbAdapter.setTransactionSuccessful();
		} finally {
			mDbAdapter.endTransaction();
		}
		return bState;
	}

	private void deleteDbSerieListEntity() {
		List<SerieEntity> inDbList = getSerieEntityLst();
		for (SerieEntity entity : inDbList) {
			delete(entity);
		}
	}

	@Deprecated
	private void deleteDeprecatedSerieListEntity(SerieListEntity listEntity) {
		List<SerieEntity> inDbList = getSerieEntityLst();
		List<SerieEntity> deprecatedList = new ArrayList<SerieEntity>();
		if (inDbList == null) {
			return;
		}
		for (SerieEntity inDbEntity : inDbList) {
			boolean bDeprecated = true;
			for (SerieEntity inNetEntity : listEntity.dataList) {
				if (inDbEntity.id.equals(inNetEntity.id)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (SerieEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	/**
	 * 插入MachineListEntity
	 * 
	 * @param entities
	 * @return
	 */
	public boolean insert(MachineListEntity listEntity) {
		boolean bState = false;
		mDbAdapter.beginTransaction();

		try {

			deleteDeprecatedMachineListEntity(listEntity);
			for (MachineEntity entity : listEntity.dataList) {
				if (insertOrUpdate(entity)) {
					bState = true;
				}
			}
			mDbAdapter.setTransactionSuccessful();
		} finally {
			mDbAdapter.endTransaction();
		}

		return bState;
	}

	private void deleteDeprecatedMachineListEntity(MachineListEntity listEntity) {
		List<MachineEntity> inDbList = getMachineEntityLst("");
		List<MachineEntity> deprecatedList = new ArrayList<MachineEntity>();
		if (inDbList == null) {
			return;
		}
		for (MachineEntity inDbEntity : inDbList) {
			boolean bDeprecated = true;
			for (MachineEntity inNetEntity : listEntity.dataList) {
				if (inDbEntity.barcode.equals(inNetEntity.barcode)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (MachineEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	/**
	 * 插入BookTypeListEntity
	 * 
	 * @param entities
	 * @return
	 */
	public boolean insert(BookTypeListEntity listEntity) {
		boolean bState = false;
		mDbAdapter.beginTransaction();
		try {

			for (BookTypeEntity entity : listEntity.dataList) {
				if (insert(entity)) {
					bState = true;
				}
			}
			mDbAdapter.setTransactionSuccessful();
		} finally {
			mDbAdapter.endTransaction();
		}
		return bState;
	}

	// ============================
	// Entity insert
	// ============================
	public boolean insert(BookEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {
			String sql = "insert into " + HctConstants.DB_TABLE_NAME_BOOK_LST
					+ " (id," + "bookName," + "booktypeId," + "booktypeName,"
					+ "seriesId," + "bookFileSize," + "versionCode,"
					+ "download_url," + "childSeriesId," + "bookZipState,"
					+ "progress," + "childSeriesName," + "bCanUpdate,"
					+ "column,"// 当DB_VERSION = 10时新增的字段,用来区分是“技术资料”还是“调试维修”
					+ "displayName,"// 当DB_VERSION = 12时新增的字段
					+ "bookFileLongSize,"// 当DB_VERSION = 12时新增的字段
					+ "suffix," + "currentBookFileLongSize,"// 当DB_VERSION =
															// 12时新增的字段
					+ "currentBookId)"// 当DB_VERSION = 12时新增的字段
					+ " values " + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
			mDbAdapter.execSQL(sql, new Object[] { entity.id, entity.bookName,
					entity.booktypeId, entity.booktypeName, entity.seriesId,
					entity.bookFileSize, entity.versionCode,
					entity.download_url, entity.childSeriesId,

					entity.bookZipState, entity.progress,
					entity.childSeriesName, entity.bCanUpdate, entity.columnId,
					entity.displayName, entity.bookFileLongSize, entity.suffix,
					entity.currentBookFileLongSize, entity.currentBookId });
			return true;
		}
	}

	public boolean insert(SerieEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {
			String sql = "insert into " + HctConstants.DB_TABLE_NAME_SERIE_LST
					+ " (id," + "seriesTypeName," + "name)" + " values "
					+ "(?,?,?);";
			mDbAdapter.execSQL(sql, new Object[] { entity.id,
					entity.seriesTypeName, entity.name });
			return true;
		}
	}

	public boolean insert(MachineEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {
			String sql = "insert into "
					+ HctConstants.DB_TABLE_NAME_MACHINE_LST + " (seriesId,"
					+ "barcode," + "childSeriesId," + "id," + "name)"
					+ " values " + "(?,?,?,?,?);";
			mDbAdapter.execSQL(sql, new Object[] { entity.seriesId,
					entity.barcode, entity.childSeriesId, entity.id,
					entity.name });
			return true;
		}
	}

	public boolean insert(BookTypeEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {
			String sql = "insert into "
					+ HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST + " (id,"
					+ "name)" + " values " + "(?,?);";
			mDbAdapter.execSQL(sql, new Object[] { entity.id, entity.name });
			return true;
		}
	}

	public boolean insert(ChildSerieEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {

			StringBuffer sb = new StringBuffer();
			for (String bookId : entity.childSeriesBookIdList) {
				sb.append(bookId);
				if (!entity.childSeriesBookIdList.get(
						entity.childSeriesBookIdList.size() - 1).equals(bookId)) {
					sb.append(",");
				}

			}
			String sql = "insert into "
					+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
					+ " (childSeriesId," + "childSeriesName," + "seriesId,"
					+ "childSeriesBookIdList)" + " values " + "(?,?,?,?);";
			mDbAdapter.execSQL(sql, new Object[] { entity.childSeriesId,
					entity.childSeriesName, entity.seriesId, sb.toString() });
			return true;
		}
	}
/**
 * 插入machinesBooks表
 */
	public boolean insert(MachineBooksEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {

			StringBuffer sb = new StringBuffer();
			for (String bookId : entity.machineBookIdList) {
				sb.append(bookId);
				if (!entity.machineBookIdList.get(
						entity.machineBookIdList.size() - 1).equals(bookId)) {
					sb.append(",");
				}
			}
			String sql = "insert into "
					+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST
					+ " (machineId," + "machineBookIdList)" + " values "
					+ "(?,?);";
			mDbAdapter.execSQL(sql,
					new Object[] { entity.machineId, sb.toString() });
			return true;
		}
	}

	// ============================
	// Entity isExists
	// ============================

	/**
	 * 判断此条BookEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(BookEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_BOOK_LST + " where bookName='"
				+ entity.bookName + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	/**
	 * 判断此条SerieEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(SerieEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_SERIE_LST + " where id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	/**
	 * 判断此条MachineEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(MachineEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_MACHINE_LST + " where id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	/**
	 * 判断此条ChildSerieEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(MachineBooksEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST
				+ " where machineId='" + entity.machineId + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	/**
	 * 判断此条ChildSerieEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(ChildSerieEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
				+ " where childSeriesId='" + entity.childSeriesId + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	/**
	 * 判断此条BookTypeEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(BookTypeEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST + " where id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	// ============================
	// Entity Lst
	// ============================

	public MachineListEntity fuzzySearchMachineListEntity(String keyWord) {
		Cursor cursor = fuzzySearchMachineListEntityCursor(keyWord);
		MachineListEntity listEntity = new MachineListEntity();

		// mActivity.startManagingCursor(cursor);
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			MachineEntity entity = new MachineEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int nameIndex = cursor.getColumnIndex("name");
			int barcodeIndex = cursor.getColumnIndex("barcode");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int idIndex = cursor.getColumnIndex("id");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.name = cursor.getString(nameIndex);
			entity.barcode = cursor.getString(barcodeIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.id = cursor.getString(idIndex);

			if (listEntity.dataList == null) {
				listEntity.dataList = new ArrayList<MachineEntity>();
			}
			listEntity.dataList.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();

		return listEntity;
	}

	/**
	 * 通过用户输入的条形码获取机型实体
	 * 
	 * @param sUserInput
	 * @return
	 */
	public MachineEntity getMachineEntity(String sUserInput) {
		String name = sUserInput;
		String barCode = "";
		if (sUserInput.length() >= 5) {
			barCode = sUserInput.substring(0, 5);
		}

		Cursor cursor = getMachineEntityCursor(name, barCode);
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		MachineEntity entity = null;
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			entity = new MachineEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int nameIndex = cursor.getColumnIndex("name");
			int barcodeIndex = cursor.getColumnIndex("barcode");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int idIndex = cursor.getColumnIndex("id");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.name = cursor.getString(nameIndex);
			entity.barcode = cursor.getString(barcodeIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.id = cursor.getString(idIndex);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return entity;
	}

	public BookEntity getBookEntityUseBookName(String bookName) {
		Cursor cursor = getBookEntityCursorUseBookName(bookName);
		BookEntity entity = initBookEntity(cursor);
		cursor.close();
		return entity;
	}

	public BookEntity getBookEntity(String id) {
		Cursor cursor = getBookEntityCursor(id);
		BookEntity entity = initBookEntity(cursor);

		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return entity;
	}

	public BookEntity getBookEntityUseCurrentId(String currentBookId) {
		Cursor cursor = getBookEntityUseCurrentIdCursor(currentBookId);
		BookEntity entity = initBookEntity(cursor);

		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return entity;
	}

	private BookEntity initBookEntity(Cursor cursor) {
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		BookEntity entity = new BookEntity();
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {

			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int booktypeIdIndex = cursor.getColumnIndex("booktypeId");
			int bookNameIndex = cursor.getColumnIndex("bookName");
			int booktypeNameIndex = cursor.getColumnIndex("booktypeName");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int bookFileSizeIndex = cursor.getColumnIndex("bookFileSize");
			int versionCodeIndex = cursor.getColumnIndex("versionCode");
			int download_urlIndex = cursor.getColumnIndex("download_url");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int bookZipStateIndex = cursor.getColumnIndex("bookZipState");
			int progressIndex = cursor.getColumnIndex("progress");
			int bCanUpdateIndex = cursor.getColumnIndex("bCanUpdate");

			int columnIndex = cursor.getColumnIndex("column");
			int displayNameIndex = cursor.getColumnIndex("displayName");
			int bookFileLongSizeIndex = cursor
					.getColumnIndex("bookFileLongSize");
			int currentBookFileLongSizeIndex = cursor
					.getColumnIndex("currentBookFileLongSize");
			int currentBookIdIndex = cursor.getColumnIndex("currentBookId");

			int doWhatClickIndex = cursor.getColumnIndex("doWhatClick");

			int suffixIndex = cursor.getColumnIndex("suffix");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.bookName = cursor.getString(bookNameIndex);
			entity.booktypeId = cursor.getString(booktypeIdIndex);
			entity.booktypeName = cursor.getString(booktypeNameIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.bookFileSize = cursor.getString(bookFileSizeIndex);
			entity.versionCode = cursor.getString(versionCodeIndex);
			entity.download_url = cursor.getString(download_urlIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			entity.bookZipState = cursor.getString(bookZipStateIndex);
			entity.progress = cursor.getInt(progressIndex);
			entity.bCanUpdate = cursor.getString(bCanUpdateIndex);

			entity.columnId = cursor.getString(columnIndex);
			entity.displayName = cursor.getString(displayNameIndex);
			entity.bookFileLongSize = cursor.getString(bookFileLongSizeIndex);
			entity.currentBookFileLongSize = cursor
					.getString(currentBookFileLongSizeIndex);
			entity.currentBookId = cursor.getString(currentBookIdIndex);
			entity.doWhatClick = cursor.getString(doWhatClickIndex);

			entity.suffix = cursor.getString(suffixIndex);
		}
		return entity;
	}

	private boolean contains(List<BookEntity> entities, BookEntity addEnrity) {
		for (BookEntity entity : entities) {
			if (entity.id.equals(addEnrity.id)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 查询指定seriesId(系列)下的ChildSerieEntity列表
	 * 
	 * @param seriesId
	 * @param type
	 *            0所有 1已下载
	 * @return
	 */
	public List<ChildSerieEntity> getChildSerieListEntityUseSerieId(
			String seriesId, int type) {
		Cursor cursor = getChildSeriesBooksLstCursor(seriesId);
		List<ChildSerieEntity> childSeriesBooksList = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			ChildSerieEntity entity = new ChildSerieEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int childSeriesBookIdListIndex = cursor
					.getColumnIndex("childSeriesBookIdList");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			addBookIdList(cursor, entity, childSeriesBookIdListIndex);
			if (childSeriesBooksList == null) {
				childSeriesBooksList = new ArrayList<ChildSerieEntity>();
			}
			childSeriesBooksList.add(entity);
		}
		cursor.close();
		return childSeriesBooksList;
	}

	public List<ChildSerieEntity> getChildSerieListEntityAndTechDataBooksUseSerieId(
			String seriesId) {
		Cursor cursor = getChildSeriesBooksLstCursor(seriesId);
		List<ChildSerieEntity> childSeriesBooksList = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			ChildSerieEntity entity = new ChildSerieEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int childSeriesBookIdListIndex = cursor
					.getColumnIndex("childSeriesBookIdList");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			addBookIdList(cursor, entity, childSeriesBookIdListIndex);
			addTechDataBookEntityList(entity);
			if (childSeriesBooksList == null) {
				childSeriesBooksList = new ArrayList<ChildSerieEntity>();
			}
			childSeriesBooksList.add(entity);
		}
		cursor.close();
		return childSeriesBooksList;
	}

	/**
	 * 查询指定seriesId(系列)下的ChildSerieEntity列表及BookEntity
	 * 
	 * @param seriesId
	 * @return
	 */
	public List<ChildSerieEntity> getChildSerieListEntityAndBooksUseSerieId(
			String seriesId) {

		Cursor cursor = getChildSeriesBooksLstCursor(seriesId);
		List<ChildSerieEntity> childSeriesBooksList = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			ChildSerieEntity entity = new ChildSerieEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int childSeriesBookIdListIndex = cursor
					.getColumnIndex("childSeriesBookIdList");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			addBookIdList(cursor, entity, childSeriesBookIdListIndex);
			addBookEntityList(entity);
			if (childSeriesBooksList == null) {
				childSeriesBooksList = new ArrayList<ChildSerieEntity>();
			}
			childSeriesBooksList.add(entity);
		}
		cursor.close();
		return childSeriesBooksList;
	}

	private void addTechDataBookEntityList(ChildSerieEntity entity) {
		for (String bookId : entity.childSeriesBookIdList) {
			BookEntity inDbEntity = getBookEntity(bookId);
			if (entity.dataList == null) {
				entity.dataList = new ArrayList<BookEntity>();
			}
			if (inDbEntity.id.equals("")
					|| !inDbEntity.booktypeId.equals("001")) {
				continue;
			}
			entity.dataList.add(inDbEntity);
		}

	}

	private void addBookEntityList(ChildSerieEntity entity) {
		for (String bookId : entity.childSeriesBookIdList) {
			BookEntity inDbEntity = getBookEntity(bookId);
			if (entity.dataList == null) {
				entity.dataList = new ArrayList<BookEntity>();
			}
			if (inDbEntity.id.equals("")
					|| inDbEntity.bookFileLongSize.equals("0")) {// 当书籍大小为0kb则不显示
				continue;
			}
			entity.dataList.add(inDbEntity);
		}

	}

	private void addBookIdList(Cursor cursor, ChildSerieEntity entity,
			int childSeriesBookIdListIndex) {
		String sChildSeriesBookIdList = cursor
				.getString(childSeriesBookIdListIndex);
		String[] childSeriesBookIdArray = sChildSeriesBookIdList.split(",");
		if (childSeriesBookIdArray != null) {
			for (String bookId : childSeriesBookIdArray) {
				entity.childSeriesBookIdList.add(bookId);
			}
		}
	}

	public List<BookEntity> getBooksUseChildSeriesId(String seriesId,
			String childSeriesId) {
		Cursor cursor = getChildSeriesBooksLstCursor(seriesId, childSeriesId);

		ChildSerieEntity entity = new ChildSerieEntity();
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int childSeriesBookIdListIndex = cursor
					.getColumnIndex("childSeriesBookIdList");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			addBookIdList(cursor, entity, childSeriesBookIdListIndex);
			addBookEntityList(entity);

		}
		cursor.close();
		return entity.dataList;
	}

	/**
	 * 查询指定seriesId(系列)下的图书列表
	 * 
	 * @param seriesId
	 * @return
	 */
	public BookListEntity getBookListEntityUseSerieId(String seriesId,
			String childSeriesId) {

		Cursor cursor = getBookLstCursor(seriesId, childSeriesId);
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		BookListEntity listEntity = new BookListEntity();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			BookEntity entity = new BookEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int booktypeIdIndex = cursor.getColumnIndex("booktypeId");
			int booktypeNameIndex = cursor.getColumnIndex("booktypeName");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int bookFileSizeIndex = cursor.getColumnIndex("bookFileSize");
			int versionCodeIndex = cursor.getColumnIndex("versionCode");
			int download_urlIndex = cursor.getColumnIndex("download_url");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int bookZipStateIndex = cursor.getColumnIndex("bookZipState");
			int progressIndex = cursor.getColumnIndex("progress");
			int bCanUpdateIndex = cursor.getColumnIndex("bCanUpdate");
			int bookNameIndex = cursor.getColumnIndex("bookName");

			int columnIndex = cursor.getColumnIndex("column");
			int displayNameIndex = cursor.getColumnIndex("displayName");
			int bookFileLongSizeIndex = cursor
					.getColumnIndex("bookFileLongSize");
			int currentBookFileLongSizeIndex = cursor
					.getColumnIndex("currentBookFileLongSize");
			int currentBookIdIndex = cursor.getColumnIndex("currentBookId");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.booktypeId = cursor.getString(booktypeIdIndex);
			entity.booktypeName = cursor.getString(booktypeNameIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.bookFileSize = cursor.getString(bookFileSizeIndex);
			entity.versionCode = cursor.getString(versionCodeIndex);
			entity.download_url = cursor.getString(download_urlIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			entity.bookZipState = cursor.getString(bookZipStateIndex);
			entity.progress = cursor.getInt(progressIndex);
			entity.bCanUpdate = cursor.getString(bCanUpdateIndex);
			entity.bookName = cursor.getString(bookNameIndex);
			entity.columnId = cursor.getString(columnIndex);
			entity.displayName = cursor.getString(displayNameIndex);
			entity.bookFileLongSize = cursor.getString(bookFileLongSizeIndex);
			entity.currentBookFileLongSize = cursor
					.getString(currentBookFileLongSizeIndex);
			entity.currentBookId = cursor.getString(currentBookIdIndex);
			if (listEntity.dataList == null) {
				listEntity.dataList = new ArrayList<BookEntity>();
			}
			listEntity.dataList.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return listEntity;
	}

	private List<BookEntity> getBooksListUseMachineId(String machineId) {
		List<BookEntity> list = null;
		Cursor cursor = getMachineBooksLstCursor(machineId);
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			MachineBooksEntity entity = new MachineBooksEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int machineIdIndex = cursor.getColumnIndex("machineId");

			int machineBookIdListIndex = cursor
					.getColumnIndex("machineBookIdList");

			addBookIdList(cursor, entity, machineBookIdListIndex);
			entity._id = cursor.getInt(_idIndex);
			entity.machineId = cursor.getString(machineIdIndex);

			addBookEntityList(entity);

			list = entity.dataList;
		}
		cursor.close();

		return list;
	}

	private void addBookEntityList(MachineBooksEntity entity) {
		for (String bookId : entity.machineBookIdList) {
			BookEntity inDbEntity = getBookEntity(bookId);
			if (entity.dataList == null) {
				entity.dataList = new ArrayList<BookEntity>();
			}
			if (inDbEntity.id.equals("")) {
				continue;
			}
			entity.dataList.add(inDbEntity);
		}

	}

	public List<MachineBooksEntity> getMachineBooksListEntity() {
		Cursor cursor = getMachineBooksLstCursor("");
		List<MachineBooksEntity> machineBooksList = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			MachineBooksEntity entity = new MachineBooksEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int machineIdIndex = cursor.getColumnIndex("machineId");

			int machineBookIdListIndex = cursor
					.getColumnIndex("machineBookIdList");

			entity._id = cursor.getInt(_idIndex);
			entity.machineId = cursor.getString(machineIdIndex);

			addBookIdList(cursor, entity, machineBookIdListIndex);
			if (machineBooksList == null) {
				machineBooksList = new ArrayList<MachineBooksEntity>();
			}
			machineBooksList.add(entity);
		}
		cursor.close();
		return machineBooksList;
	}

	private void addBookIdList(Cursor cursor, MachineBooksEntity entity,
			int machineBookIdListIndex) {
		String sMachineBookIdList = cursor.getString(machineBookIdListIndex);
		String[] machineBookIdArray = sMachineBookIdList.split(",");
		if (machineBookIdArray != null) {
			for (String bookId : machineBookIdArray) {
				entity.machineBookIdList.add(bookId);
			}
		}
	}

	/**
	 * 查询指定seriesId(系列)下的图书列表
	 * 
	 * @param seriesId
	 * @return
	 */
	@Deprecated
	public BookListEntity getBookListEntityUseSerieId(String seriesId, int type) {

		Cursor cursor = getBookLstCursor(seriesId, type);
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		BookListEntity listEntity = new BookListEntity();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			BookEntity entity = new BookEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int booktypeIdIndex = cursor.getColumnIndex("booktypeId");
			int booktypeNameIndex = cursor.getColumnIndex("booktypeName");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int bookFileSizeIndex = cursor.getColumnIndex("bookFileSize");
			int versionCodeIndex = cursor.getColumnIndex("versionCode");
			int download_urlIndex = cursor.getColumnIndex("download_url");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int bookZipStateIndex = cursor.getColumnIndex("bookZipState");
			int progressIndex = cursor.getColumnIndex("progress");
			int bCanUpdateIndex = cursor.getColumnIndex("bCanUpdate");
			int bookNameIndex = cursor.getColumnIndex("bookName");

			int columnIndex = cursor.getColumnIndex("column");
			int displayNameIndex = cursor.getColumnIndex("displayName");
			int bookFileLongSizeIndex = cursor
					.getColumnIndex("bookFileLongSize");
			int currentBookFileLongSizeIndex = cursor
					.getColumnIndex("currentBookFileLongSize");
			int currentBookIdIndex = cursor.getColumnIndex("currentBookId");
			int suffixIndex = cursor.getColumnIndex("suffix");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.booktypeId = cursor.getString(booktypeIdIndex);
			entity.booktypeName = cursor.getString(booktypeNameIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.bookFileSize = cursor.getString(bookFileSizeIndex);
			entity.versionCode = cursor.getString(versionCodeIndex);
			entity.download_url = cursor.getString(download_urlIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			entity.bookZipState = cursor.getString(bookZipStateIndex);
			entity.progress = cursor.getInt(progressIndex);
			entity.bCanUpdate = cursor.getString(bCanUpdateIndex);
			entity.bookName = cursor.getString(bookNameIndex);
			entity.columnId = cursor.getString(columnIndex);
			entity.displayName = cursor.getString(displayNameIndex);
			entity.bookFileLongSize = cursor.getString(bookFileLongSizeIndex);
			entity.currentBookFileLongSize = cursor
					.getString(currentBookFileLongSizeIndex);
			entity.currentBookId = cursor.getString(currentBookIdIndex);
			entity.suffix = cursor.getString(suffixIndex);

			if (listEntity.dataList == null) {
				listEntity.dataList = new ArrayList<BookEntity>();
			}

			listEntity.dataList.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return listEntity;
	}

	/**
	 * 从Db查询出SerieEntity
	 * 
	 * @return
	 */
	public SerieEntity getSerieEntity(String seriesId) {
		Cursor cursor = getSerieLstCursor(seriesId);
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		SerieEntity entity = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			entity = new SerieEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int nameIndex = cursor.getColumnIndex("name");
			int seriesTypeNameIndex = cursor.getColumnIndex("seriesTypeName");
			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.name = cursor.getString(nameIndex);
			entity.seriesTypeName = cursor.getString(seriesTypeNameIndex);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return entity;
	}

	/**
	 * 从Db查询出List<SerieEntity>
	 * 
	 * @return
	 */
	public List<SerieEntity> getSerieEntityLst() {
		Cursor cursor = getSerieLstCursor("");
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		List<SerieEntity> list = new ArrayList<SerieEntity>();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			SerieEntity entity = new SerieEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int nameIndex = cursor.getColumnIndex("name");
			int seriesTypeNameIndex = cursor.getColumnIndex("seriesTypeName");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.name = cursor.getString(nameIndex);
			entity.seriesTypeName = cursor.getString(seriesTypeNameIndex);
			list.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return list;
	}

	/**
	 * 从Db查询出List<MachineEntity>
	 * 
	 * @param seriesId
	 *            为0则查询全部
	 * @return
	 */
	public List<MachineEntity> getMachineEntityLst(String seriesId) {
		Cursor cursor = getMachineLstCursor(seriesId);
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		List<MachineEntity> list = new ArrayList<MachineEntity>();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			MachineEntity entity = new MachineEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int nameIndex = cursor.getColumnIndex("name");
			int barcodeIndex = cursor.getColumnIndex("barcode");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int idIndex = cursor.getColumnIndex("id");

			entity._id = cursor.getInt(_idIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.name = cursor.getString(nameIndex);
			entity.barcode = cursor.getString(barcodeIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.id = cursor.getString(idIndex);
			list.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return list;
	}

	/**
	 * 从Db查询出List<BookTypeEntity>
	 * 
	 * @return
	 */
	public List<BookTypeEntity> getBookTypeEntityLst() {
		Cursor cursor = getBookTypeLstCursor();
		/**
		 * 把获取的Cursor对象交给Activity管理， 这样Cursor的生命周期便能和Activity自动同步， 省去自己手动管理。
		 */
		// mActivity.startManagingCursor(cursor);
		List<BookTypeEntity> list = new ArrayList<BookTypeEntity>();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			BookTypeEntity entity = new BookTypeEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int nameIndex = cursor.getColumnIndex("name");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.name = cursor.getString(nameIndex);
			list.add(entity);
		}
		// mActivity.stopManagingCursor(cursor);
		cursor.close();
		return list;
	}

	/**
	 * FIXME
	 * 
	 * @param columnId
	 * @param sKeyword
	 * @return
	 */
	public ArrayList<BookEntity> getBookLstUseColumnIdAndMachineId(
			MachineEntity machineEntity, String columnId, String sKeyword) {

		List<BookEntity> bookEntities = getBooksListUseMachineId(machineEntity.id);
		if (bookEntities == null) {
			return null;
		}
		Cursor cursor = getBookLstCursorUseColumnId(columnId, sKeyword);
		ArrayList<BookEntity> list = null;
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			BookEntity entity = new BookEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int booktypeIdIndex = cursor.getColumnIndex("booktypeId");
			int booktypeNameIndex = cursor.getColumnIndex("booktypeName");
			int seriesIdIndex = cursor.getColumnIndex("seriesId");
			int bookFileSizeIndex = cursor.getColumnIndex("bookFileSize");
			int versionCodeIndex = cursor.getColumnIndex("versionCode");
			int download_urlIndex = cursor.getColumnIndex("download_url");
			int childSeriesIdIndex = cursor.getColumnIndex("childSeriesId");
			int childSeriesNameIndex = cursor.getColumnIndex("childSeriesName");

			int bookZipStateIndex = cursor.getColumnIndex("bookZipState");
			int progressIndex = cursor.getColumnIndex("progress");
			int bCanUpdateIndex = cursor.getColumnIndex("bCanUpdate");
			int bookNameIndex = cursor.getColumnIndex("bookName");

			int columnIndex = cursor.getColumnIndex("column");
			int displayNameIndex = cursor.getColumnIndex("displayName");
			int bookFileLongSizeIndex = cursor
					.getColumnIndex("bookFileLongSize");
			int currentBookFileLongSizeIndex = cursor
					.getColumnIndex("currentBookFileLongSize");
			int currentBookIdIndex = cursor.getColumnIndex("currentBookId");

			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.booktypeId = cursor.getString(booktypeIdIndex);
			entity.booktypeName = cursor.getString(booktypeNameIndex);
			entity.seriesId = cursor.getString(seriesIdIndex);
			entity.bookFileSize = cursor.getString(bookFileSizeIndex);
			entity.versionCode = cursor.getString(versionCodeIndex);
			entity.download_url = cursor.getString(download_urlIndex);
			entity.childSeriesId = cursor.getString(childSeriesIdIndex);
			entity.childSeriesName = cursor.getString(childSeriesNameIndex);

			entity.bookZipState = cursor.getString(bookZipStateIndex);
			entity.progress = cursor.getInt(progressIndex);
			entity.bCanUpdate = cursor.getString(bCanUpdateIndex);
			entity.bookName = cursor.getString(bookNameIndex);

			entity.columnId = cursor.getString(columnIndex);
			entity.displayName = cursor.getString(displayNameIndex);
			entity.bookFileLongSize = cursor.getString(bookFileLongSizeIndex);
			entity.currentBookFileLongSize = cursor
					.getString(currentBookFileLongSizeIndex);
			entity.currentBookId = cursor.getString(currentBookIdIndex);
			if (contains(bookEntities, entity)) {
				if (list == null) {
					list = new ArrayList<BookEntity>();
				}
				list.add(entity);
			}

		}
		cursor.close();
		return list;
	}

	// ============================
	// Cusrsor
	// ============================

	/**
	 * XXX 查询指定name 或barcode能匹配的machine,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * ,其中用户输入的条码前5位能匹配上machine的barcode
	 * 
	 * @return
	 */
	private Cursor getMachineEntityCursor(String name, String barcode) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_MACHINE_LST
				+ " where name='" + name + "'" + " or barcode ='" + barcode
				+ "'" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 模糊搜索MachineList(barcode不重复)
	 * 
	 * @param keyWord
	 * @return
	 */
	private Cursor fuzzySearchMachineListEntityCursor(String keyWord) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_MACHINE_LST
				+ " where name like'%" + keyWord + "%'" + " or barcode like'%"
				+ keyWord + "%'" + " group by barcode" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询指定download_url的book,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getBookEntityCursorUseBookName(String bookName) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where bookName='" + bookName + "'" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询指定id的book,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getBookEntityCursor(String id) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where id='" + id + "'" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	private Cursor getBookEntityUseCurrentIdCursor(String currentBookId) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where currentBookId='" + currentBookId + "'"
				+ " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询books,获取结果游标(Cursor), asc:最早insert的会先被查询到 不展视0kb的书籍，wuhs
	 * 
	 * @param type
	 *            0所有 1已下载
	 * @return
	 */
	private Cursor getBookLstCursor(String seriesId, int type) {
		String sql = "";
		if (!seriesId.equals("")) {
			if (type == 0) {
				sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
						+ " where seriesId='" + seriesId + "'"
						+ " and bookFileLongSize!='0'" + " order by _id asc";
			} else {
				sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
						+ " where seriesId='" + seriesId
						+ "' and bookZipState='book.zip.state.analisis.done'"
						+ " and bookFileLongSize!='0'" + " order by _id asc";
			}

		} else if (seriesId.equals("")) {
			if (type == 0) {
				sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
						+ " where bookFileLongSize!='0'" + " order by _id asc";
			} else {
				sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
						+ " where bookZipState='book.zip.state.analisis.done'"
						+ " and bookFileLongSize!='0'" + " order by _id asc";
			}

		}
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询books,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getBookLstCursor(String seriesId, String childSeriesId) {
		String sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where seriesId='" + seriesId + "'" + " and childSeriesId='"
				+ childSeriesId + "'" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * XXX 查询machineBooks,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getMachineBooksLstCursor(String machineId) {
		String sql = "";
		if (!machineId.equals("")) {
			sql = "select * from "
					+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST
					+ " where machineId='" + machineId + "'"
					+ " order by _id asc";
		} else if (machineId.equals("")) {
			sql = "select * from "
					+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST

					+ " order by _id asc";
		}

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * FIXME 查询childSeriesBooks,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getChildSeriesBooksLstCursor(String seriesId) {
		String sql = "";
		if (!seriesId.equals("")) {
			sql = "select * from "
					+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
					+ " where seriesId='" + seriesId + "'"
					+ " order by childSeriesName";
		} else if (seriesId.equals("")) {
			sql = "select * from "
					+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
					+ " order by childSeriesName";
		}

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	private Cursor getChildSeriesBooksLstCursor(String seriesId,
			String childSeriesId) {
		String sql = "select * from "
				+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
				+ " where seriesId='" + seriesId + "'" + " and childSeriesId='"
				+ childSeriesId + "'" + " order by _id asc";

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询series,获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getSerieLstCursor(String seriesId) {

		String sql = "";
		if (!seriesId.equals("")) {
			sql = "select * from " + HctConstants.DB_TABLE_NAME_SERIE_LST
					+ " where id='" + seriesId + "'" + " order by _id asc";
		} else if (seriesId.equals("")) {
			sql = "select * from " + HctConstants.DB_TABLE_NAME_SERIE_LST
					+ " order by _id asc";
		}

		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询machines,获取结果游标(Cursor), desc:最新insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getMachineLstCursor(String seriesId) {
		String sql = "";
		if (!seriesId.equals("")) {
			sql = "select * from " + HctConstants.DB_TABLE_NAME_MACHINE_LST
					+ " where seriesId='" + seriesId + "'"
					+ " order by _id asc";
		} else if (seriesId.equals("")) {
			sql = "select * from " + HctConstants.DB_TABLE_NAME_MACHINE_LST
					+ " order by _id desc";
		}
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 查询book_types,获取结果游标(Cursor), desc:最新insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getBookTypeLstCursor() {
		String sql = "select * from "
				+ HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST
				+ " order by _id desc";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	/**
	 * 获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getBookLstCursorUseColumnId(String columnId, String sKeyword) {

		String sql = "select * from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where column='" + columnId + "'"
				+ " and displayName like'%" + sKeyword + "%'"
				+ " order by _id asc";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	// ============================
	// get _id
	// ============================

	private int get_idFromDb(MachineBooksEntity entity) {
		String sql = "select _id from "
				+ HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST + " where "
				+ "machineId='" + entity.machineId + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	private int get_idFromDb(ChildSerieEntity entity) {
		String sql = "select _id from "
				+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST + " where "
				+ "childSeriesId='" + entity.childSeriesId + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	private int get_idFromDb(BookEntity entity) {
		String sql = "select _id from " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " where " + "bookName='" + entity.bookName + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	private int get_idFromDb(SerieEntity entity) {
		String sql = "select _id from " + HctConstants.DB_TABLE_NAME_SERIE_LST
				+ " where " + "id='" + entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	private int get_idFromDb(MachineEntity entity) {
		String sql = "select _id from "
				+ HctConstants.DB_TABLE_NAME_MACHINE_LST + " where " + "id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	private int get_idFromDb(BookTypeEntity entity) {
		String sql = "select _id from "
				+ HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST + " where " + "id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

	// ============================
	// Entity update
	// ============================
	private void update(BookEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " set bCanUpdate='" + entity.bCanUpdate + "'"
				+ ",booktypeId='" + entity.booktypeId + "'" + ",seriesId='"
				+ entity.seriesId
				+ "'"
				+ ",bookFileSize='"
				+ entity.bookFileSize
				+ "'"
				+ ",versionCode='"
				+ entity.versionCode
				+ "'"
				+ ",download_url='"
				+ entity.download_url
				+ "'"
				+ ",childSeriesId='"
				+ entity.childSeriesId
				+ "'"
				// + ",bookZipState='" + entity.bookZipState + "'"
				// + ",progress='" + entity.progress + "'"
				+ ",childSeriesName='" + entity.childSeriesName + "'"
				+ ",column='" + entity.columnId + "'" + ",suffix='"
				+ entity.suffix + "'"

				+ ",displayName='" + entity.displayName + "'"
				+ ",bookFileLongSize='" + entity.bookFileLongSize + "'"
				+ ",id='" + entity.id + "'" + " where bookName='"
				+ entity.bookName + "'";

		mDbAdapter.execSQL(sql);
	}

	private void update(BookEntity entity, boolean bhasNewVersionCode) {
		String sql = "";
		if (bhasNewVersionCode) {
			sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
					+ " set bCanUpdate='" + entity.bCanUpdate
					+ "'"
					+ ",booktypeId='"
					+ entity.booktypeId
					+ "'"
					+ ",seriesId='"
					+ entity.seriesId
					+ "'"
					+ ",bookFileSize='"
					+ entity.bookFileSize
					+ "'"
					+ ",versionCode='"
					+ entity.versionCode
					+ "'"
					+ ",download_url='"
					+ entity.download_url
					+ "'"
					+ ",childSeriesId='"
					+ entity.childSeriesId
					+ "'"
					// + ",bookZipState='" + entity.bookZipState + "'"
					// + ",progress='" + entity.progress + "'"
					+ ",childSeriesName='" + entity.childSeriesName + "'"
					+ ",column='" + entity.columnId + "'"

					+ ",suffix='" + entity.suffix + "'"

					+ ",displayName='" + entity.displayName + "'"
					+ ",bookFileLongSize='" + entity.bookFileLongSize + "'"
					+ ",currentBookFileLongSize='"
					+ entity.currentBookFileLongSize + "'" + ",id='"
					+ entity.id + "'" + ",currentBookId='"
					+ entity.currentBookId + "'" + " where bookName='"
					+ entity.bookName + "'";
		} else if (!bhasNewVersionCode) {
			sql = "update "
					+ HctConstants.DB_TABLE_NAME_BOOK_LST
					+ " set booktypeId='"
					+ entity.booktypeId
					+ "'"
					// + ",bCanUpdate='" + entity.bCanUpdate + "'"
					+ ",seriesId='" + entity.seriesId + "'" + ",bookFileSize='"
					+ entity.bookFileSize + "'" + ",versionCode='"
					+ entity.versionCode
					+ "'"
					+ ",download_url='"
					+ entity.download_url
					+ "'"
					+ ",childSeriesId='"
					+ entity.childSeriesId
					+ "'"
					// + ",bookZipState='" + entity.bookZipState + "'"
					// + ",progress='" + entity.progress + "'"
					+ ",childSeriesName='" + entity.childSeriesName + "'"
					+ ",column='" + entity.columnId + "'"

					+ ",suffix='" + entity.suffix + "'"

					+ ",displayName='" + entity.displayName + "'" + ",id='"
					+ entity.id + "'" + " where bookName='" + entity.bookName
					+ "'";
		}

		mDbAdapter.execSQL(sql);
	}

	private void update(SerieEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_SERIE_LST
				+ " set name='" + entity.name + "'" + " , seriesTypeName='"
				+ entity.seriesTypeName + "'" + " where id='" + entity.id + "'";

		mDbAdapter.execSQL(sql);
	}

	/**
	 * update MachineEntity(barcode作为唯一标示)
	 * 
	 * @param entity
	 */
	private void update(MachineEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_MACHINE_LST
				+ " set name='" + entity.name + "'" + ",seriesId='"
				+ entity.seriesId + "'" + ",childSeriesId='"
				+ entity.childSeriesId + "'" + ",barcode='" + entity.barcode
				+ "'" + " where id='" + entity.id + "'";

		mDbAdapter.execSQL(sql);
	}

	private void update(BookTypeEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_TYPE_LST
				+ " set name='" + entity.name + "'" + " where id='" + entity.id
				+ "'";

		mDbAdapter.execSQL(sql);
	}

	private void update(MachineBooksEntity entity) {
		StringBuffer sb = new StringBuffer();
		for (String bookId : entity.machineBookIdList) {
			sb.append(bookId);
			if (!entity.machineBookIdList.get(
					entity.machineBookIdList.size() - 1).equals(bookId)) {
				sb.append(",");
			}

		}
		String sql = "update " + HctConstants.DB_TABLE_NAME_MACHINE_BOOK_LST
				+ " set machineBookIdList='" + sb.toString() + "'"
				+ " where machineId='" + entity.machineId + "'";

		mDbAdapter.execSQL(sql);
	}

	private void update(ChildSerieEntity entity) {
		StringBuffer sb = new StringBuffer();
		for (String bookId : entity.childSeriesBookIdList) {
			sb.append(bookId);
			if (!entity.childSeriesBookIdList.get(
					entity.childSeriesBookIdList.size() - 1).equals(bookId)) {
				sb.append(",");
			}

		}
		String sql = "update "
				+ HctConstants.DB_TABLE_NAME_CHILD_SERIES_BOOK_LST
				+ " set childSeriesName='" + entity.childSeriesName + "'"
				+ ",seriesId='" + entity.seriesId + "'"
				+ ",childSeriesBookIdList='" + sb.toString() + "'"
				+ " where childSeriesId='" + entity.childSeriesId + "'";

		mDbAdapter.execSQL(sql);
	}

	public void updateBookZipState(BookEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " set bookZipState='" + entity.bookZipState + "'"
				+ " where bookName='" + entity.bookName + "'";

		mDbAdapter.execSQL(sql);
	}

	public void updateBookProgress(BookEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " set progress='" + entity.progress + "'"
				+ " where bookName='" + entity.bookName + "'";

		mDbAdapter.execSQL(sql);
	}

	public void updateBookBCannotUpdate(BookEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " set bCanUpdate='"
				+ HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE + "'"
				+ ",currentBookId='" + "" + "'" + ",currentBookFileLongSize='"
				+ "" + "'" + " where bookName='" + entity.bookName + "'";

		mDbAdapter.execSQL(sql);
	}

	public void updateBookOnWhatClick(BookEntity entity) {
		String sql = "update " + HctConstants.DB_TABLE_NAME_BOOK_LST
				+ " set doWhatClick='" + entity.doWhatClick + "'"
				+ " where bookName='" + entity.bookName + "'";

		mDbAdapter.execSQL(sql);
	}
}
